# 简单的HTTP服务器，用于测试PWA功能
# 使用方法: python simple_server.py

import http.server
import socketserver
import os
import mimetypes
import json
import cgi
import urllib.parse
from datetime import datetime

# 上传目录配置
UPLOAD_DIR = "static/uploads"
if not os.path.exists(UPLOAD_DIR):
    os.makedirs(UPLOAD_DIR, exist_ok=True)

class PWAHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        """处理GET请求"""
        # 获取图片列表API
        if self.path == '/api/images':
            self.handle_get_images()
            return
        
        # 处理单页应用的路由
        if not os.path.exists(self.path[1:]) and not self.path.startswith('/static/'):
            # 如果文件不存在且不是静态资源，返回index.html
            self.path = '/'
        
        # 处理manifest.json的特殊情况
        if self.path == '/manifest.json':
            self.path = '/manifest.json'
        
        return super().do_GET()
    
    def handle_get_images(self):
        """获取图片列表"""
        try:
            images = []
            for filename in os.listdir(UPLOAD_DIR):
                if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.gif', '.webp')):
                    file_path = os.path.join(UPLOAD_DIR, filename)
                    file_stat = os.stat(file_path)
                    images.append({
                        'name': filename,
                        'url': f'/uploads/{filename}',
                        'size': file_stat.st_size,
                        'modified': datetime.fromtimestamp(file_stat.st_mtime).isoformat()
                    })
            
            # 按修改时间排序，最新的在前
            images.sort(key=lambda x: x['modified'], reverse=True)
            
            response = {
                'success': True,
                'images': images
            }
            
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response).encode('utf-8'))
            
        except Exception as e:
            print(f"获取图片列表错误: {e}")
            response = {
                'success': False,
                'message': f'获取图片列表失败: {str(e)}'
            }
            self.send_response(500)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response).encode('utf-8'))

    def end_headers(self):
        # 添加PWA所需的HTTP头
        self.send_header('Service-Worker-Allowed', '/')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        
        # 为特定文件类型添加正确的MIME类型
        if self.path.endswith('.js'):
            self.send_header('Content-Type', 'application/javascript')
        elif self.path.endswith('.json'):
            self.send_header('Content-Type', 'application/json')
        elif self.path.endswith('.css'):
            self.send_header('Content-Type', 'text/css')
        elif self.path.endswith('.png'):
            self.send_header('Content-Type', 'image/png')
        elif self.path.endswith('.jpg') or self.path.endswith('.jpeg'):
            self.send_header('Content-Type', 'image/jpeg')
        elif self.path.endswith('.svg'):
            self.send_header('Content-Type', 'image/svg+xml')
        
        super().end_headers()
    
    def do_POST(self):
        """处理POST请求，包括图片上传"""
        if self.path == '/api/upload-image':
            self.handle_image_upload()
        elif self.path == '/api/delete-image':
            self.handle_delete_image()
        else:
            self.send_error(404)
    
    def handle_image_upload(self):
        """处理图片上传"""
        try:
            # 获取内容长度
            content_length = int(self.headers['Content-Length'])
            
            # 读取multipart数据
            post_data = self.rfile.read(content_length)
            
            # 解析multipart/form-data
            content_type = self.headers['Content-Type']
            boundary = content_type.split('boundary=')[1].strip('"')
            
            # 查找图片数据
            parts = post_data.split(f'--{boundary}'.encode())
            
            for part in parts:
                if b'filename=' in part and b'Content-Type:' in part:
                    # 提取文件名
                    filename_start = part.find(b'filename="') + 10
                    filename_end = part.find(b'"', filename_start)
                    filename = part[filename_start:filename_end].decode('utf-8')
                    
                    # 提取文件数据
                    header_end = part.find(b'\r\n\r\n')
                    file_data = part[header_end + 4:]
                    
                    # 移除末尾的boundary标记
                    if file_data.endswith(b'\r\n'):
                        file_data = file_data[:-2]
                    
                    # 生成安全的文件名
                    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
                    safe_filename = f"{timestamp}_{filename}"
                    safe_filename = safe_filename.replace(' ', '_').replace('..', '_')
                    
                    # 保存文件
                    file_path = os.path.join(UPLOAD_DIR, safe_filename)
                    
                    with open(file_path, 'wb') as f:
                        f.write(file_data)
                    
                    # 返回成功响应
                    response = {
                        'success': True,
                        'imageUrl': f'/uploads/{safe_filename}',
                        'message': '图片上传成功'
                    }
                    
                    self.send_response(200)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    self.wfile.write(json.dumps(response).encode('utf-8'))
                    return
            
            # 没有找到图片文件
            response = {
                'success': False,
                'message': '未找到图片文件'
            }
            self.send_response(400)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response).encode('utf-8'))
            
        except Exception as e:
            print(f"上传处理错误: {e}")
            response = {
                'success': False,
                'message': f'服务器处理错误: {str(e)}'
            }
            self.send_response(500)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response).encode('utf-8'))
    
    def handle_delete_image(self):
        """处理图片删除"""
        try:
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            data = json.loads(post_data.decode('utf-8'))
            
            image_url = data.get('imageUrl')
            if not image_url:
                self.send_error(400, "缺少图片URL")
                return
            
            # 从URL中提取文件名
            filename = os.path.basename(image_url)
            file_path = os.path.join(UPLOAD_DIR, filename)
            
            if os.path.exists(file_path):
                os.remove(file_path)
                response = {
                    'success': True,
                    'message': '图片删除成功'
                }
                self.send_response(200)
            else:
                response = {
                    'success': False,
                    'message': '图片文件不存在'
                }
                self.send_response(404)
            
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response).encode('utf-8'))
            
        except Exception as e:
            print(f"删除图片错误: {e}")
            response = {
                'success': False,
                'message': f'删除图片失败: {str(e)}'
            }
            self.send_response(500)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response).encode('utf-8'))

if __name__ == "__main__":
    PORT = 8081  # 使用不同的端口避免冲突
    
    # 切换到magazine目录
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    
    with socketserver.TCPServer(("", PORT), PWAHTTPRequestHandler) as httpd:
        print(f"🚀 PWA测试服务器启动!")
        print(f"📱 请访问: http://localhost:{PORT}")
        print(f"🧪 测试页面: http://localhost:{PORT}/offline-test.html")
        print(f"📊 PWA状态: http://localhost:{PORT}/offline-test.html")
        print(f"📸 图片管理: http://localhost:{PORT}/admin-enhanced.html")
        print(f"🧪 上传测试: http://localhost:{PORT}/upload-test.html")
        print(f"📁 上传目录: {UPLOAD_DIR}")
        print(f"🔧 按 Ctrl+C 停止服务器")
        
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n👋 服务器已停止")
            httpd.shutdown()